/*
Libreria lettura ADS1217
ADC 24bit 8ch
HW TEST 1
Manuel Baldo
*/

#define DOUT_adc	PORTGbits.RG7       				 
#define DRDY_adc	PORTCbits.RC13
#define DIN_adc		LATGbits.LATG8
#define SCLK_adc	LATGbits.LATG6
#define CS_adc		LATBbits.LATB13		 
#define SYNC_pin	LATCbits.LATC14   // min 3 tosc


//ADRRESS
#define SETUP 	0
#define MUX		1
#define ACR		2
#define IDAC1	3
#define IDAC2	4
#define ODAC 	5
#define DIO		6
#define DIR		7
#define DEC0	8
#define MDEC1	9
#define OCR0	10
#define OCR1	11
#define OCR2	12
#define FSR0	13
#define FSR1	14
#define FSR2	15

//COMMANDS
#define WREG		(unsigned)0x50  // 0101 xxxx Indirizzo Registro
#define RREG		(unsigned)0x10  // 0001 xxxx Indirizzo Registro
#define RDATA		(unsigned)0x01	// Richiesta lettura 24 bit
#define RDATAC		(unsigned)0b00000011	// Start lettura 24 bit continua
#define STOPC		(unsigned)0b00001111	// Stop lettura 24 bit continua

//Commands per calibrazione
#define SYSOCAL		(unsigned)0b11110011  // Mettere a 0V ingressi ed abilitare la calibrazione offset
#define SYSGCAL 	(unsigned)0b11110100  // Mettere a VREF infresso ed abilitare la clibrazione gain
#define SELFCAL		(unsigned)0b11110000  // Calibra Gain ed Offset autonomamente
#define SELFOCAL	(unsigned)0b11110001  // Calibra Gain ed Offset autonomamente
#define SELFGCAL	(unsigned)0b11110010  // Calibra Gain ed Offset autonomamente

#define ADC_SLEEP 	(unsigned)0b11111101 // Comando sleep, strobe su SCLK esce dal sleep
#define ADC_RESET 	(unsigned)0b11111110 // Comando RESET
#define DSYNC		(unsigned)0b11111100 // La conversione attende il primo CLK
#define WAKEUP		(unsigned)0x00 // SOLO ADS1216, ESCE DA SLEEP O DA DSYNC
#define RESET		(unsigned)0xFE


void Init_ADS1247(void);
void Setup_ADS1217(unsigned char setup);
void Delay_SCK(void);
void Delay_ns(long ns); 
void Write_Byte(unsigned char byte);
unsigned long Read_bits(unsigned char bits);
long ADS1217_OUT(unsigned char time_out);
unsigned char Read_REG(unsigned char addr);
void PGA_ADS1217(unsigned char pga);
void Filter_ADS1217(unsigned char Data_format,unsigned char SMODE,unsigned int decimatore);